package controllers

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/sessions"
	"strings"
)

type Feedback struct {
	Ctx iris.Context
}

func (c *Feedback) PostSubmit() interface{} {
	channel := c.Ctx.PostValueDefault("channel", "mini")
	content := c.Ctx.PostValue("content")

	var userId int64
	if strings.EqualFold(channel, "wechat") {
		token := c.Ctx.GetHeader("token")
		claims, err := utils.ParseToken(token)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("解析token出错：%s", err.Error()), "")
		}
		userId = utils.Atoi64(claims.Id)
	} else {
		session := sessions.Get(c.Ctx)
		userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
	}

	var err error
	var db *xorm.Engine

	db, err = datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	feedback := new(models.Feedback)
	feedback.UserId = userId
	feedback.Content = content
	_, err = db.InsertOne(feedback)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("反馈失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功提交", "")
}